#!/usr/bin/perl
use IO::Socket;


my $seriesDir = $ARGV[0];
unless($seriesDir) {
    print "Usage: $0 </path/to/series>\n";
    exit 1;
}

open MEDX, "medx|";
my $medxPort;
my $foundPorts = 0;
do {
    my $line = <MEDX>;
#    print $line;
    
    chomp $line;
    if($line =~ /MEDx server listening on port (\d+)/) {
	$foundPorts++;
	if($foundPorts == 2) {
	    $medxPort = $1;
#	    print "Parent: medx port is $medxPort\n";
	}
    }
    
} until defined $medxPort;

# now tell MEDx to open the series
openSeries($medxPort, $seriesDir);

# now wait for MEDx to exit
while(<MEDX>) {
#    print;
}
close(MEDX);

# clean up log files if no medx processes are running
my @medxProcesses = `ps -ef | grep xc | grep -v grep`;
if(scalar(@medxProcesses) == 0) {
    `rm -f /tmp/MEDx_*.log`;
}

exit 0;


sub openSeries {
    my ($medxPort, $seriesDir) = @_;

    my $sock = new IO::Socket::INET (
				     PeerAddr => 'localhost',
				     PeerPort => $medxPort,
				     Proto => 'tcp',
				     );
    die "Could not create connection to MEDx: $!\n" unless $sock;
    
    sleep 1;

    print $sock "
<<
    MessageType RegisterClient
    Name (DICOMBrowse)
    KillOnExit? false 
>>
";

    sleep 1;

    print $sock "
<<
    MessageType    InvokeFunction
    Function       NewFolder
>>
";
    
    sleep 3;
    
    print $sock '
<<
    MessageType    InvokeFunction
    Function       OpenImage
    FileFormat                     Dicom
    DICOMLogFlag                   0
    DICOMLogDirectory              (/tmp)
    DICOMCTImageVolume             (acquisition-based)
    DICOMMRImageVolume             (acquisition-based)
    DICOMPETImageGatedGrouping     (volume-based)
    DICOMPETImageDynamicGrouping   (volume-based)
    DICOMPETImageDynamicStartTimes (acquisition-time-based)
    FileNames                      [ ('.$seriesDir.') ]
>>
';

    close($sock);
}
